package com.zretc.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.zretc.entity.Seller;
import com.zretc.service.SellerDataService;
import com.zretc.service.SellerService;
import com.zretc.service.impl.SellerDataServiceImpl;
import com.zretc.service.impl.SellerServiceImpl;
import com.zretc.util.MD5Util;

/**
 * @wentao
 * 店铺信息管理
 * Servlet implementation class SellerInfoServlet
 */
@WebServlet("/back/sellerInfo")
@MultipartConfig
public class SellerInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SellerDataService sellerDateService = new SellerDataServiceImpl();
	private SellerService sellerService = new SellerServiceImpl();

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取操作类型
		String op = request.getParameter("op");
		if(op == null) {
			op = "";
		}
		switch (op) {
		case "data":
			// 获取主页显示数据
			showIndexPageData(request, response);
			break;
		case "detail":
			// 获取详细信息
			getSellerDetail(request, response);
			break;
		case "update":
			// 修改数据
			updateSellerInfo(request, response);
			break;
		case "updatePassword":
			// 修改密码
			updatePassword(request, response);
			break;

		default:
			break;
		}
	}
	
	/**
	 * @author wentao
	 * 主页显示数据
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void showIndexPageData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取店铺编号
		Integer sellerId = Integer.valueOf(request.getParameter("sellerId"));
		
		// 新订单数量
		int newOrderNumber = sellerDateService.newOrderNumber(sellerId);
		// 已发货数量
		int shippedOrderNumber = sellerDateService.shippedOrderNumber(sellerId);
		// 已完成数量
		int finishOrderNumber = sellerDateService.finishOrderNumber(sellerId);
		// 全部订单数量
		int allOrderNumber = sellerDateService.allOrderNumber(sellerId);
		// 等待发货数量
		int waitOrderNumber = sellerDateService.waitOrderNumber(sellerId);
		// 收藏店铺数量
		int collectShopUserNumber = sellerDateService.collectShopUserNumber(sellerId);
		// 购买商品用户数数量
		int shoppingProductUserNumber = sellerDateService.shoppingProductUserNumber(sellerId);
		// 收藏商品用户数数量
		int collectProductUserNumber = sellerDateService.collectProductUserNumber(sellerId);
		// 最近下单时间
		String lastOrderDate = sellerDateService.lastOrderDate(sellerId);
		// 全部评论数量
		int allCommentNumber = sellerDateService.allCommentNumber(sellerId);
		// 已回复数量
		int replyCommentNumber = sellerDateService.replyCommentNumber(sellerId);
		// 等待回复数量
		int waitReplyCommentNumber = sellerDateService.waitReplyCommentNumber(sellerId);
		
		// 获取销售额
		Map<String, Float> monthSales = sellerDateService.monthSales(sellerId);
		Calendar calendar = Calendar.getInstance();
		Integer maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		List<String> salesDate = new ArrayList<String>();
		List<Float> salesMoney = new ArrayList<>();
		
		// 获取日下单用户数
		Map<String, Integer> placeTheOrderMap = sellerDateService.placeTheOrderUserNumber(sellerId);
		List<String> placeTheOrderDate = new ArrayList<String>();
		List<Integer> placeTheOrderNumber = new ArrayList<>();
		for(int i = 1 ; i <= maxDay; i++) {
			String temp = "";
			if(i<10) {
				temp = "0"+i;
			}else {
				temp = ""+i;
			}
			if(!monthSales.containsKey(temp)) {
				salesMoney.add(0.0f);
			}else {
				salesMoney.add(monthSales.get(temp));
			}
			if(!placeTheOrderMap.containsKey(temp)) {
				placeTheOrderNumber.add(0);
			}else {
				placeTheOrderNumber.add(placeTheOrderMap.get(temp));
			}
			placeTheOrderDate.add(temp);
			salesDate.add(temp);
		}
		
		// 用map存储所有数据
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("newOrderNumber", newOrderNumber);
		data.put("shippedOrderNumber", shippedOrderNumber);
		data.put("finishOrderNumber", finishOrderNumber);
		data.put("allOrderNumber", allOrderNumber);
		data.put("waitOrderNumber", waitOrderNumber);
		data.put("collectShopUserNumber", collectShopUserNumber);
		data.put("shoppingProductUserNumber", shoppingProductUserNumber);
		data.put("collectProductUserNumber", collectProductUserNumber);
		data.put("lastOrderDate", lastOrderDate);
		data.put("allCommentNumber", allCommentNumber);
		data.put("replyCommentNumber", replyCommentNumber);
		data.put("waitReplyCommentNumber", waitReplyCommentNumber);
		data.put("salesDate", salesDate);
		data.put("salesMoney", salesMoney);
		data.put("placeTheOrderNumber", placeTheOrderNumber);
		data.put("placeTheOrderDate", placeTheOrderDate);
		// 转换成json格式并响应
		String json = new Gson().toJson(data);
		response.setContentType("application/json");
		response.getWriter().write(json);
		
	}
	public void getSellerDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取商家编号
		Integer sellerId = Integer.valueOf(request.getParameter("sellerId"));
		// 获取商家信息
		Seller seller = sellerService.getSellerDetail(sellerId);
		// 转换成json格式并响应
		String json = new Gson().toJson(seller);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
	public void updateSellerInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 获取商家logo
		String sellerLogo = request.getParameter("sellerLogo");
		String json = request.getParameter("data");
		Map<String,Object> fromJson = new Gson().fromJson(json, Map.class);
		System.out.println(fromJson);
		// 获取商家编号
		Integer sellerId = Integer.valueOf(request.getParameter("sellerId"));
		
		// 文件处理
		Part part = request.getPart("file");
		if(part.getSize() > 0) {
			// 允许的文件图片类型
			String allowImgType ="image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
			
			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			
			// 判断上传的文件MIME类型是否在指定的允许类型集合
			if(allowImgTypeList.contains(contentType)==true) {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);	
				// 随机数
				int random = (int) (Math.random()*1000+1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);
				
				// 将文件存储在指定服务器中
				File file = new File("D:\\upload\\images");
				
				// 将文件写入指定位置
				String filePath = file.getPath() + File.separator + fileName + fileSuffix; // E:\fileupload\images\1.jpg
				part.write(filePath);
				
				sellerLogo = fileName + fileSuffix;
			}
		}
		// 获取商家名称
		String sellerShopName = request.getParameter("sellerShopName");
		// 获取商家电话
		String sellerPhone = request.getParameter("sellerPhone");
		// 获取商家地址
		String sellerAddress = request.getParameter("sellerAddress");
		// 更新
		Seller seller = new Seller(sellerId, null, null, sellerAddress, sellerPhone, sellerShopName, sellerLogo, 1);
		sellerService.modifyBySellerId(seller);
		
		// 修改session
		HttpSession session = request.getSession();
		Seller s = (Seller)session.getAttribute("seller");
		s.setSellerLogo(sellerLogo);
		s.setSellerAddress(sellerAddress);
		s.setSellerPhone(sellerPhone);
		s.setSellerShopName(sellerShopName);
		session.setAttribute("seller", s);
	}
	public void updatePassword(HttpServletRequest request, HttpServletResponse response) {
		// 获取商家编号
		Integer sellerId = Integer.valueOf(request.getParameter("sellerId"));
		// 获取要修改的密码
		String sellerPassword = request.getParameter("sellerPassword");
		String md5 = MD5Util.getMd5(sellerPassword);
		// 更新
		sellerService.updatePassword(sellerId, md5);
	}

}
